<template>
    <div>
        <el-drawer
            :title="title"
            :visible.sync="is_show"
            @closed="closed"
            :wrapperClosable="false"
        >
            <div class="container">
                <el-form :model="form" ref="apply-form" :rules="rules" label-position="left" :validate-on-rule-change="false">
                    <div class="title">专利信息</div>
                    <el-form-item
                        label="申报主体"
                        prop="pattern"
                        label-width="170px"
                    >
                        <el-cascader
                            placeholder="请选择申报主体"
                            :options="partternOptions"
                            v-model="form.pattern">
					    </el-cascader>
                        <!-- <el-select v-model="form.pattern">
                            <el-option
                                v-for="item in partternOptions"
                                :key="item"
                                :label="item.label"
                                :value="item.value"
                                placeholder="请选择申报主体"
                            ></el-option>
                        </el-select> -->
                    </el-form-item>
                    <div v-if="form.pattern[1] == 'a'">
                        <el-form-item
                            label="技术领域"
                            prop="territory"
                            label-width="170px"
                        >
                            <el-input v-model="form.territory" placeholder="请输入技术领域"></el-input>
                        </el-form-item>
                        <el-form-item
                            label="技术背景"
                            prop="background"
                            label-width="170px"
                        >
                            <el-input v-model="form.background" placeholder="请输入技术背景"></el-input>
                        </el-form-item>
                    </div>
                    <div v-if="form.pattern[0] == 1 || form.pattern[1] == 'a'">
                        <el-form-item
                            label="技术问题"
                            prop="problem"
                            label-width="170px"
                        >
                            <el-input v-model="form.problem" placeholder="请输入技术问题"></el-input>
                        </el-form-item>
                        <el-form-item
                            label="技术方案"
                            prop="plan"
                            label-width="170px"
                        >
                            <el-input v-model="form.plan" placeholder="请输入技术方案"></el-input>
                        </el-form-item>
                        <el-form-item
                            label="项目优势"
                            prop="advantage"
                            label-width="170px"
                        >
                            <el-input v-model="form.advantage" placeholder="请输入项目优势"></el-input>
                        </el-form-item>
                    </div>
                    <el-form-item
                        v-if="form.pattern[1] == 'a'"
                        label="具体实施方式"
                        prop="way"
                        label-width="170px"
                    >
                        <el-input v-model="form.way" placeholder="请输入具体实施方式"></el-input>
                    </el-form-item>
                    <el-form-item
                        label="附图"
                        prop="img"
                        label-width="170px"
                    >
                        <el-upload
                            ref="upload"
                            :action="uploadImgUrl"
                            :on-remove="handleRemove"
							:on-success="handleSuccess"
                            :file-list="fileList"
							:auto-upload="true"
                            :before-upload="beforeUpload" multiple>
							<el-button slot="trigger" type="primary">上传图片</el-button>
							<div slot="tip" class="el-upload__tip" style="margin-top: 0px;">只能上传 jpg/jpeg/png/gif 文件，且不超过10M</div>
						</el-upload>
                    </el-form-item>
                    <el-form-item
                        v-if="form.pattern[1] == 'b' || form.pattern[0] == 3"
                        label="附件"
                        prop="file"
                        label-width="170px"
                    >
                        <el-upload
							class="upload-demo input-left"
							ref="upload2"
							:action="uploadFileUrl"
							:on-remove="handleRemove2"
							:on-success="handleSuccess2"
							:file-list="fileList2"
							:auto-upload="true"
							:before-upload="beforeUpload2"
							multiple>
                            <el-button slot="trigger" type="primary">上传文件</el-button>
                            <div slot="tip" class="el-upload__tip" style="margin-top: 0px;">只能上传.docx 文件，且不超过100M</div>
                        </el-upload>
                    </el-form-item>
                    <el-form-item
                        label="拟申报专利类型"
                        prop="type"
                        label-width="170px"
                    >
                        <el-select
                            multiple
                            v-model="form.type"
                            placeholder="请选择拟申报专利类型"
                        >
                            <el-option
                                v-for="(item, index) in patentOptions"
                                :key="index"
                                :label="item"
                                :value="item"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item
                        label="拟申报专利名称"
                        prop="patent_name"
                        label-width="170px"
                    >
                        <el-input v-model="form.patent_name" placeholder="请输入拟申报专利名称"></el-input>
                    </el-form-item>
                    <div class="title">专利权人信息</div>
                    <el-form-item
                        label="专利权人"
                        prop="patent_user"
                        label-width="170px"
                    >
                        <el-autocomplete
							v-model="form.patent_user"
							:fetch-suggestions="querySearch"
							:trigger-on-focus="false"
							placeholder="请输入专利权人"
							:validate-event='false'>
						</el-autocomplete>
                    </el-form-item>
                    <div class="title">发明人信息</div>
                    <el-form-item
                        label="发明人姓名"
                        prop="user_name"
                        label-width="170px"
                    >
                        <el-input v-model="form.user_name" placeholder="请输入发明人姓名"></el-input>
                    </el-form-item>
                    <el-form-item
                        label="第一发明人身份证号码"
                        prop="id_card"
                        label-width="170px"
                    >
                        <el-input v-model="form.id_card" placeholder="请输入第一发明人身份证号码"></el-input>
                    </el-form-item>
                    <div class="title">联络人信息</div>
                    <el-form-item
                        label="联络人（只写一个）"
                        prop="liaisons"
                        label-width="170px"
                    >
                        <el-input v-model="form.liaisons" placeholder="请输入联络人"></el-input>
                    </el-form-item>
                    <el-form-item
                        label="联络人电话"
                        prop="liaisons_tel"
                        label-width="170px"
                    >
                        <el-input v-model="form.liaisons_tel" placeholder="请输入联络人电话"></el-input>
                    </el-form-item>
                    <el-form-item
                        label="联络人邮箱"
                        prop="liaisons_email"
                        label-width="170px"
                    >
                        <el-input v-model="form.liaisons_email" placeholder="请输入联络人邮箱"></el-input>
                    </el-form-item>
                    <div class="title">自选服务</div>
                    <el-form-item
                        label="代理人"
                        prop="agent_id"
                        label-width="170px"
                    >
                        <el-select
                            v-model="form.agent_id"
                            placeholder="请选择代理人"
                            filterable
                        >
                            <el-option
                                v-for="item in agentOption"
                                :key="item.id"
                                :value="item.id"
                                :label="item.name"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item
                        label="自助加速"
                        prop="service"
                        label-width="170px"
                    >
                        <el-select
                            v-model="form.service"
                            :disabled="true"
                        >
                            <el-option
                                v-for="(item, index) in serviceOptions"
                                :key="index"
                                :label="item.label"
                                :value="item.value"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </div>
            <div class="footer clearfloat">
                <el-button @click="is_show = false" >取消</el-button>
                <el-button type="primary" @click="submit" v-no-more-click:3000>确认</el-button>
            </div>
        </el-drawer>
    </div>
</template>

<script>
import { validateName, validateId, validatePhone, validateEmail } from '~/util/index'
export default {
    data() {
        return {
            title: '添加订单',
            is_show: false,
            form: {
                pattern: [1],
                territory: '',
                background: '',
                problem: '',
                plan: '',
                advantage: '',
                way: '',
                img: [],
                file: [],
                type: [],
                patent_name: '',
                patent_user: '',
                user_name: '',
                liaisons: '',
                liaisons_tel: '',
                liaisons_email: '',
                agent_id: null,
                service: 'C'
            },
            fileList: [],
            fileList2: [],
            partternOptions: [
                {
                    value: 1,
                    label: 'idea模式'
                },
                {
					value: 2,
					label: '技术交底模式',
					children: [{
						value: 'a',
						label: '在线填写'
					}, {
						value: 'b',
						label: '上传文件'
					}]
                },
                {
					value: 3,
					label: '定向导航'
                }
            ],
            serviceOptions: [
                {
                    value: 'A',
                    label: '10个工作日'
                }, {
                    value: 'B',
                    label: '20个工作日'
                }, {
                    value: 'C',
                    label: '30个工作日'
                }
            ],
            agentOption: [],
            allPatent: [],
            patentOptions: ['发明专利', '实用新型', '外观设计', '不确定'],
            uploadImgUrl: global.baseurl + '/api/upload/img',
            uploadFileUrl: global.baseurl + '/api/upload/file',
        }
    },
    computed: {
        rules() {
            let rules = {
                pattern: [{required: true, message: '请选择申报主体', trigger: 'blur'}],
                territory: [{required: false, message: '请输入技术领域', trigger: 'blur'}],
                background: [{required: false, message: '请输入技术背景', trigger: 'blur'}],
                problem: [{required: false, message: '请输入技术问题', trigger: 'blur'}],
                plan: [{required: false, message: '请输入技术方案', trigger: 'blur'}],
                advantage: [{required: false, message: '请输入项目优势', trigger: 'blur'}],
                way: [{required: false, message: '请输入具体实施方式', trigger: 'blur'}],
                img: [{required: false, message: '请上传附图'}],
                file: [{required: false, message: '请上传附件'}],
                type: [{required: true, message: '请选择拟申报专利类型', trigger: 'blur'}],
                patent_name: [{required: true, message: '请输入拟申报专利名称', trigger: 'blur'}],
                patent_user: [{required: true, message: '请输入专利权人', trigger: 'blur'}],
                user_name: [{required: true, validator: validateName, trigger: 'blur'}],
                id_card: [{required: true, validator: validateId, trigger: 'blur'}],
                liaisons: [{required: true, message: '请输入发明人姓名', trigger: 'blur'}],
                liaisons_tel: [{required: true, validator: validatePhone, trigger: 'blur'}],
                liaisons_email: [{required: true, validator: validateEmail, trigger: 'blur'}],
                agent_id: [{required: true, message: '请选择代理人', trigger: 'blur'}],
                service: [{required: true, trigger: 'blur'}],
            }
            if (this.form.pattern[0] == 1 || this.form.pattern[0] == 2) {
                rules.problem[0].required = true
                rules.plan[0].required = true
                rules.advantage[0].required = true
                if (this.form.pattern[0] == 2) {
                    rules.territory[0].required = true
                    rules.background[0].required = true
                    rules.way[0].required = true
                }
            }

            // 只有上传文件 附图附件必选
            if (this.form.pattern[1] == 'b') {
                rules.img[0].required = true
                rules.file[0].required = true
            } else if (this.form.pattern[0] == 3) { // 定向导航附件必选
                rules.file[0].required = true
            }
            return rules
        }
    },
    created() {
        this.getAllPatent()
        this.getAllAgent()
    },
    methods: {
        showOn(id) {
            if (id) {

            } else {
                this.getAllPatent()
                this.getAllAgent()
                this.is_show = true
                this.$nextTick(() => {
                    this.$refs['apply-form'].clearValidate()
                })
            }
        },
        submit() {
            this.$refs['apply-form'].validate(valid => {
                if (valid) {
                   this.submitPost()
                } else {
                    this.$message({
                        type: 'error',
                        message: '校验失败，请检查填写的资料'
                    })
                    return false;
                }
            });
        },
        submitPost() {
            let params = Object.assign({},this.form)
            if (params.pattern[0] == 1 || params.pattern[1] == 'a') {
                delete params.file
                if (params.pattern[0] == 1) {
                    params.territory = ''
                    params.background = ''
                    params.way = ''
                }
            }
            if (params.pattern[0] == 3 || params.pattern[1] == 'b') {
                params.file = this.form.file.join('&')
                params.territory = ''
                params.background = ''
                params.way = ''
                params.problem = ''
                params.plan = ''
                params.advantage = ''
            }
            delete params.type
            delete params.img
            delete params.pattern
            params.pattern = this.form.pattern[0]
            params.type = this.form.type.join(',')
            params.img = this.form.img.join('&')
            this.$axios.post('/api/order/adminCreate', params).then(res => {
                if (res.data.code == 200) {
                    this.$message({
                        type: 'success',
                        message: this.title + '成功'
                    })
                    this.is_show = false
                    this.$emit('refresh')
                } else {
                    this.$message({
                        type: 'error',
                        message: res.data.message
                    })
                }
            }).catch(e => {
            })
        },
        getAllPatent() {
            this.$axios.get('api/order/patent').then(res => {
                if (res.data.code == 200) {
                    let arr = [];
                    let arrItem = {}
                    for (let i = 0; i < res.data.data.length; i++) {
                        //element的模糊匹配组件el-autocomplete指定：必须数组的每个元素是个对象，并且有value属性
                        let arrItem = {}
                        arrItem.value = res.data.data[i];
                        arr.push(arrItem)
                    }
                    this.allPatent = arr
                }
            })
        },
        getAllAgent() {
            this.$axios.get('api/user/agent').then(res => {
                if (res.data.code == 200) {
                   this.agentOption = res.data.data
                } else {
                    this.$message({
                        type: 'error',
                        message: '获取代理人信息失败'
                    })
                }
            })
        },
        handleRemove(file, fileList) {
            let that = this;
            //从服务器也删除此文件
            that.$axios.delete('/api/delete/file', {
                data: {
                    path: that.fileList[fileList.length]
                }
            })
            that.fileList.splice(fileList.length, 1)
            that.form.img.splice(fileList.length, 1)
        },
        handleRemove2(file, fileList) {
            let that = this;
            //从服务器也删除此文件
            that.$axios.delete('/api/delete/file', {
                data: {
                    path: that.fileList2[fileList.length]
                }
            })
            that.fileList2.splice(fileList.length, 1)
            that.form.file.splice(fileList.length, 1)
        },
        handleSuccess(res, file, fileList) {
            this.fileList.push(file)
            this.form.img.push(file.response.data)
            if (this.form.pattern[0] == 3 || this.form.pattern[1] == 'b') {
                this.$refs['apply-form'].validateField('img', valid => {
                    if (valid) {
                        return false
                    } else {
                        return false
                    }
                })
            }
        },
        handleSuccess2(res, file, fileList) {
            this.fileList2.push(file)
            this.form.file.push(file.response.data)
            if (this.form.pattern[0] == 3 || this.form.pattern[1] == 'b') {
                this.$refs['apply-form'].validateField('file', valid => {
                    if (valid) {
                        return false
                    } else {
                        return false
                    }
                })
            }
        },
        beforeUpload(file) {
            let that = this;
            let canUpload = true; //是否能够上传（布尔值）
            let type = file.name.substring(file.name.lastIndexOf('.') + 1);
            //不区分大小写
            if (!/jpg|jpeg|png|gif/i.test(type)) {
                that.$message({
                    message: "文件格式只能是jpg/jpeg/png/gif",
                    type: 'warning'
                });
                canUpload = false;
            }
            let size = file.size / 1024 / 1024;
            if (size > 10) {
                that.$message({
                    message: "文件大小不能超过10M",
                    type: 'warning'
                });
                canUpload = false
            }
            return canUpload
        },
        beforeUpload2(file) {
            let that = this;
            let canUpload = true; //是否能够上传（布尔值）
            let type = file.name.substring(file.name.lastIndexOf('.') + 1)
            //不区分大小写
            if (!/docx/i.test(type)) {
                that.$message({
                    message: "文件格式只能是.docx格式",
                    type: 'warning'
                });
                canUpload = false;
            }
            let size = file.size / 1024 / 1024;
            if (size > 100) {
                that.$message({
                    message: "文件大小不能超过100M",
                    type: 'warning'
                });
                canUpload = false;
            }
            return canUpload
        },
        querySearch(queryString, cb) {
            let that = this
            let patent = this.allPatent
            let results = []
            if (patent.length > 0) {
                results = queryString ? patent.filter(that.createFilter(queryString)) : patent
            }
            cb(results)
        },
        createFilter(queryString) {
            return returnVal => {
                //===0代表从首个字符处匹配必须成功，>=0代表从任意字符处匹配必须成功
                return (returnVal.value.toLowerCase().indexOf(queryString.toLowerCase()) >= 0)
            };
        },
        closed() {
			Object.assign(this.$data, this.$options.data())
            this.$refs['apply-form'].resetFields()
        }
    }
}
</script>

<style lang="less" scoped>
/deep/.el-drawer {
    outline: none;
    .el-drawer__header {
        margin-bottom: 0;
        padding: 10px 20px;
        font-size: 20px;
        font-weight: bold;
        color: #333;
        border-bottom: 1px solid #efefef;
        text-align: center;
        span {
            outline: none;
        }
    }
    .el-drawer__body {
        .container {
            padding: 15px;
            max-height: calc(100vh - 111px);
            overflow-y: auto;
            .el-form {
                .el-cascader, .el-select, .el-autocomplete {
                    width: 100%;
                }
                .title {
                    font-size: 16px;
                    color: #333;
                    font-weight: bold;
                    margin-bottom: 10px;
                    position: relative;
                    padding-left: 10px;
                    &::before {
                        content: '';
                        position: absolute;
                        display: inline-block;
                        border-left: 3px solid #409EFF;
                        height: 21px;
                        left: 0;
                    }
                }
            }
        }
        .footer {
            border-top: 1px solid #efefef;
            padding:10px 15px;
            text-align: center;
        }
    }
}
</style>
